package com.tian.service.impl;

import com.alibaba.fastjson.JSON;
import com.tian.config.RedisConfig;
import com.tian.entity.GlobalProperty;
import com.tian.enums.BusiTypeEnum;
import com.tian.enums.FlagEnum;
import com.tian.enums.GlobalPropertyStatusEnum;
import com.tian.mapper.GlobalPropertyMapper;
import com.tian.service.GlobalPropertyService;
import com.tian.util.RedisConstantPre;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年09月22日 22:56
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 * <p>
 * 整个系统全局配置
 */
@Service
public class GlobalPropertyServiceImpl implements GlobalPropertyService {

    @Resource
    private GlobalPropertyMapper globalPropertyMapper;
    @Resource
    private RedisConfig redisConfig;

    @Override
    public boolean add(GlobalProperty globalProperty) {
        globalProperty.setBusiDesc(BusiTypeEnum.findByBusiType(globalProperty.getBusiType()).getDesc());
        globalProperty.setStatus(GlobalPropertyStatusEnum.INIT.getStatus());
        globalProperty.setCreateTime(new Date());
        int flag = globalPropertyMapper.insert(globalProperty);
        if (flag == FlagEnum.SUCCESS.getFlag()) {
            String key = RedisConstantPre.GLOBAL_PROPERTY_PRE + globalProperty.getBusiType();
            List<GlobalProperty> globalPropertyList = globalPropertyMapper.selectByBusiType(globalProperty.getBusiType());
            redisConfig.set(key, JSON.toJSONString(globalPropertyList));
            return true;
        }
        return false;
    }

    @Override
    public boolean update(GlobalProperty globalProperty) {
        String key = RedisConstantPre.GLOBAL_PROPERTY_PRE + globalProperty.getBusiType();
        //先删除缓存
        redisConfig.delete(key);
        int flag = globalPropertyMapper.updateByPrimaryKey(globalProperty);
        if (flag == FlagEnum.SUCCESS.getFlag()) {
            List<GlobalProperty> globalPropertyList = globalPropertyMapper.selectByBusiType(globalProperty.getBusiType());
            //放入缓存中
            redisConfig.set(key, JSON.toJSONString(globalPropertyList));
            return true;
        }
        return false;
    }

    @Override
    public List<GlobalProperty> queryByPage(GlobalProperty globalProperty, Integer currPage, Integer pageSize) {
        return null;
    }
}
